package com.example.com.baruffini_mele.booking4u;

import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import com.example.com.baruffini_mele.booking4u.authorization.DatabaseHandler;
import com.example.com.baruffini_mele.booking4u.authorization.JoomlaPasswordHandler;
import com.example.com.baruffini_mele.booking4u.authorization.User;

import android.app.AlertDialog;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import ldap.autenticazione;

public class MainActivity extends Activity {
	
	private static final String TAG = "MainActivity";	

   
    
    @Override
    
    /**
   	 * Handles the main interaction showing a menu.
   	 * 
   	 * @param savedInstanceState: the saved stato of the activity
   	 */	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_layout);
    }

    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main_menu, menu);
        return(super.onCreateOptionsMenu(menu));
    }
    
    
    
    /**
	 * Handles options menu items selection.
	 * If user selects "help" item, it calls HelpActivity class; if he selects "options" item,
	 * it calls SupplyCredentialsActivity class; finally, if he selects "start" option, it
	 * checks internet connection, checks if user credentials are stored in the database and
	 * then invokes SelectRoomActivity class.
	 * 
	 * @param item: the selected item of the menu
	 */	
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) 
        {
        	// if help selected
            case R.id.main_menu_help:
            	// start HelpActivity
               startActivity(new Intent(this, HelpActivity.class));
            return true;
            case R.id.main_menu_options:
            	//start SupplyCredentials
            	startActivity(new Intent(this, SupplyCredentialsActivity.class));
            return true;
            //if start selected
            case R.id.main_menu_start:
            	// check Internet connection
            	Log.v(TAG, "start");	
            
            	final Context context = getApplicationContext();
            	ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
         
                NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                boolean isConnected = activeNetwork.isConnectedOrConnecting();
                
                if(isConnected==true){ //if connected
                	Log.v(TAG, "sono connesso");	
              
            	
            	// check existing user           	
            	
            	try{
            	DatabaseHandler db = new DatabaseHandler(this);
            	
            	int existingUser = db.getUsersCount(); 
            	switch(existingUser){
		            	case 1:
		            		Log.v(TAG, "l'utente esiste");
		            		
		            		//user retrieval
		            		User u = db.getUniqueUser();
		            		String localUsername = u.getUsername();
		            		String localPassword = u.getPassword();
		            		
		            		// Authentication
		            		
		            		//Connection to remote database and hash retrieval
		          		
		            		JoomlaPasswordHandler jph = new JoomlaPasswordHandler(localUsername, localPassword);
		            		 //request remote user hash and fill savedHash property
		            		jph.postUserHashRequest();
		            		Log.v(TAG, "posted request");
		            		jph.setUserSalt(jph.estractSalt(jph.getSavedHash()));
		        			jph.setUserHash(jph.encryptLocalPassword(jph.getUserPassword()));
		        			
		        			//check match between two hashes
		        			Log.v(TAG, "userHash = "+jph.getUserHash());
		        			Log.v(TAG, "savedHash ="+jph.getSavedHash());
		        			
		        			

		            		boolean authenticated = jph.accessAuthentication();
		            			
		            		if(authenticated==true){//if authenticated, starts activity selectRoomActivity	
		            		Intent i = new Intent(getBaseContext(), SelectRoomActivity.class);
							startActivity(i);
							
							
		            		}else{//else calls wrong credential Alert dialog
		            			AlertDialog.Builder wrongCredentialsBuilder = new AlertDialog.Builder(MainActivity.this);
		                		// set title
		            			wrongCredentialsBuilder.setTitle(R.string.wrong_credentials_title);
		                    	// set dialog message
		            			wrongCredentialsBuilder.setMessage(R.string.wrong_credentials_text);
		                    	// set positive button
		            			wrongCredentialsBuilder.setPositiveButton(R.string.wrong_credentials_button, new DialogInterface.OnClickListener() {
		        					
		        					@Override
		        					public void onClick(DialogInterface dialog, int id) {
		        						// TODO Auto-generated method stub
		        						
		        						// if this button is clicked, just close
		        						// the dialog box and do nothing
		        						 dialog.cancel();
		        						
		        						
		        		
		        					}
		            			});
		            			
		            			
		            			
		            			
		            		}
							
		            	
		            	return true;
		            	
		            	case 0:
		            		//if not authenticated -> Toast errore (re insert credentials)
		            		Log.v(TAG, "l'utente non esiste");
		            		
		            		AlertDialog.Builder messageBuilder = new AlertDialog.Builder(this);
		            		// set title
		                	messageBuilder.setTitle(R.string.alert_credentials_title);
		                	// set dialog message
		                	messageBuilder.setMessage(R.string.alert_credentials_text);
		                	// set positive button
		                	messageBuilder.setPositiveButton(R.string.alert_credentials_button, new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int id) {
									// TODO Auto-generated method stub
									
									// if this button is clicked, just close
									// the dialog box and do nothing
									 dialog.cancel();
									
									//start activity SupplyCredentials
									
									Intent i = new Intent(getBaseContext(), SupplyCredentialsActivity.class);
									startActivity(i);
					
								}
							});
		                	// create alert dialog
		                	AlertDialog alertCredentials = messageBuilder.create();
		                	// show it
		                	alertCredentials.show();
		                	
		           
		            		
		            	return true;
		            	
            	}// end switch on existinguser
		            		
            	}catch(Exception e){
            		Log.e(TAG, e.getMessage());
            		
            	}
            	
                }else{// if not connected
                	Log.d(TAG, "non sono connesso");	
                	
                	
                }
            return true;	

            
        }// end switch on menu item
        return(super.onOptionsItemSelected(item));
    }  
    
}
